﻿Imports Stardust.Core
Imports Stardust.Core.Render
Imports Stardust.Core.Controls

Public Class InstallExtension

    'Private WithEvents Button As Button

    Public Event InstalledExtension(ByVal Ext As String)
    Public Event UpdatedExtensions(ByVal Extensions As List(Of String))
    Private __CurrentExtension As XElement

    Private Sub InstallExtension_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        ExtensionsPanel.Children.Clear()
        Me.Visibility = Windows.Visibility.Hidden
        e.Cancel = True
    End Sub


    Private Sub InstallExtension_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded


        'FillList(New Uri("http://storage.deepskylabs.com/stardust/ExtensionsSource.xml", UriKind.RelativeOrAbsolute))


    End Sub

    Public Sub FillList(ByVal Uri As Uri)
        If Uri.IsFile Then
            Dim Reader As New IO.StreamReader(Uri.LocalPath)
            Dim DataStr As String = Reader.ReadToEnd
            Reader.Close()

            LoadAlbum(DataStr)

        Else
            Dim WebClient As New System.Net.WebClient
            AddHandler WebClient.DownloadStringCompleted, Sub(Sender As Object, e As System.Net.DownloadStringCompletedEventArgs)
                                                              LoadAlbum(e.Result)
                                                          End Sub

            WebClient.DownloadStringAsync(Uri)

        End If
    End Sub



    Public Sub LoadAlbum(ByVal DataString As String)
        Dim xDoc As XDocument = XDocument.Parse(DataString)

        Dim data = From Extension In xDoc...<Extensions>.<Extension>

        For Each __Extension In data
            Try

                Dim Extension As XElement = __Extension

                Dim Border As New Border
                Dim Button As New StardustButton With
                    {.Text = Extension.<Title>.Value,
                     .Height = 140, .Width = 120}

                Button.Style = DirectCast(My.Application.Resources("StardustButtonStyle"), Style)


                Border.Width = 130
                Border.Height = 150

                Border.Child = Button


                Dispatcher.BeginInvoke(Sub()
                                           Button.Image = LoadImage(New Uri(Extension.<Image>.Value,
                                                                            UriKind.RelativeOrAbsolute))
                                       End Sub, Windows.Threading.DispatcherPriority.Background)

                AddHandler Button.Click,
                    Sub() ShowDetails(Extension)

                ExtensionsPanel.Children.Add(Border)

            Catch ex As Exception
                Console.WriteLine(ex.Message)
            End Try

        Next

    End Sub

    Public Sub DownloadAndInstall(ByVal UriSource As Uri)
        Dim WebClient As New System.Net.WebClient

        Dim opFile As New IO.FileInfo(String.Format("{0}\Scripts\{1}", StardustDir, UriSource.Segments(UriSource.Segments.Count - 1)))



        Console.WriteLine(opFile.FullName)

        AddHandler WebClient.DownloadProgressChanged, Sub(sender As Object,
                                                          e As System.Net.DownloadProgressChangedEventArgs)

                                                          ProgressText.Text = String.Format("{0}% downloaded of {1}", e.ProgressPercentage,
                                                                                            UriSource.OriginalString)
                                                          ProgressBar.Value = e.ProgressPercentage

                                                      End Sub

        AddHandler WebClient.DownloadFileCompleted, Sub(sender As Object,
                                                        e As System.ComponentModel.AsyncCompletedEventArgs)

                                                        ProgressText.Text = "Installing extension"
                                                        ProgressBar.IsIndeterminate = True

                                                        Dim pkg As New Extensibility.Packaging

                                                        pkg.UnpackageExtension(opFile.FullName, Nothing)

                                                        ProgressBar.IsIndeterminate = False
                                                        ProgressBar.Value = 0


                                                        Dim ScriptsDir As New IO.DirectoryInfo(StardustDir & "\Scripts")
                                                        Dim NewExtList As New List(Of String)
                                                        For Each _file As IO.FileInfo In ScriptsDir.GetFiles("*.cf")
                                                            NewExtList.Add(_file.FullName)
                                                        Next

                                                        RaiseEvent UpdatedExtensions(NewExtList)
                                                        RaiseEvent InstalledExtension(pkg.MainScriptFile)

                                                        ProgressText.Text = "Installed Extension!"

                                                    End Sub

        WebClient.DownloadFileAsync(UriSource, opFile.FullName)



    End Sub

    Public Sub ShowAndLoad()
        Me.Visibility = Windows.Visibility.Visible

        FillList(New Uri("http://storage.deepskylabs.com/stardust/ExtensionsSource.xml", UriKind.RelativeOrAbsolute))

    End Sub

    Public Sub ShowDetails(ByVal info As XElement)
        Dim Description As FlowDocument = ParseXaml(Of FlowDocument)(info.<Description>.Value)
        DescriptionBox.Document = Description

        __CurrentExtension = info

    End Sub

    Private Sub InstallButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles InstallButton.Click
        If __CurrentExtension IsNot Nothing Then
            DownloadAndInstall(New Uri(__CurrentExtension.<DownloadUri>.Value, UriKind.RelativeOrAbsolute))
        End If
    End Sub

    Private Sub InstallButton_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles InstallButton.Loaded

    End Sub
End Class
